package com.lap.framework.user;

import com.lap.framework.user.domain.User;

import java.util.Objects;

/**
 * <pre>
 * 提供微服务获取当前请求的用户信息
 * </pre>
 *
 * @author Shuisheng.Lao
 * @version 1.0.0
 */
public final class UserHandler {
    public static final ThreadLocal<User> THREAD_LOCAL = new ThreadLocal<User>();

    private UserHandler() {
    }

    /**
     * <pre>
     *  本地线程存储
     * </pre>
     *
     * @param user 用户
     */
    public static void set(User user) {
        if (Objects.isNull(THREAD_LOCAL.get())) {
            THREAD_LOCAL.set(user);
        }
    }

    /**
     * <pre>
     *  本地线程获取
     * </pre>
     *
     * @return 用户
     */
    public static User get() {
        return THREAD_LOCAL.get();
    }

    /**
     * <pre>
     * 清楚线程信息
     * </pre>
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 当前请求用户ID
     */
    public static Integer getUserId() {
        User user = get();
        if (Objects.nonNull(user)) {
            return user.getUserId();
        }
        return null;
    }

    /**
     * 获取当前登录用户名
     *
     * @return 登录用户名
     */
    public static String getUsername() {
        User user = get();
        if (Objects.nonNull(user)) {
            return user.getUsername();
        }
        return null;
    }

}
